import Cocoa
import os.log

class ScreenshotOverlayView: NSView {
    private var startPoint: NSPoint?
    private var currentRect: NSRect?
    private var isDrawing = false
    private var sizeLabel: NSTextField?
    private let logger = OSLog(subsystem: "com.macscreenshot", category: "ScreenshotOverlayView")
    
    // 截图完成的回调
    var onScreenshotComplete: ((NSImage?) -> Void)?
    
    override init(frame frameRect: NSRect) {
        super.init(frame: frameRect)
        setupView()
    }
    
    required init?(coder: NSCoder) {
        super.init(coder: coder)
        setupView()
    }
    
    private func setupView() {
        // 设置视图属性
        wantsLayer = true
        layer?.backgroundColor = NSColor.black.withAlphaComponent(0.5).cgColor
        
        // 创建大小标签
        sizeLabel = NSTextField(frame: NSRect(x: 0, y: 0, width: 100, height: 20))
        if let label = sizeLabel {
            label.isEditable = false
            label.isBordered = false
            label.backgroundColor = NSColor.black.withAlphaComponent(0.7)
            label.textColor = NSColor.white
            label.alignment = .center
            label.isHidden = true
            addSubview(label)
        }
    }
    
    override func mouseDown(with event: NSEvent) {
        startPoint = event.locationInWindow
        isDrawing = true
        currentRect = nil
        needsDisplay = true
        
        sizeLabel?.isHidden = false
    }
    
    override func mouseDragged(with event: NSEvent) {
        guard isDrawing else { return }
        updateSelectionRect(with: event.locationInWindow)
        needsDisplay = true
    }
    
    override func mouseUp(with event: NSEvent) {
        guard isDrawing, let rect = currentRect, rect.width > 1, rect.height > 1 else {
            isDrawing = false
            currentRect = nil
            needsDisplay = true
            return
        }
        
        isDrawing = false
        sizeLabel?.isHidden = true
        
        // 延迟一帧再捕获截图，确保UI更新完成
        DispatchQueue.main.async { [weak self] in
            guard let self = self else { return }
            if let screenshot = self.captureSelectedArea(rect) {
                self.onScreenshotComplete?(screenshot)
            } else {
                self.onScreenshotComplete?(nil)
            }
        }
    }
    
    override func keyDown(with event: NSEvent) {
        if event.keyCode == 53 { // ESC键
            onScreenshotComplete?(nil)
        }
    }
    
    private func updateSelectionRect(with currentPoint: NSPoint) {
        guard let start = startPoint else { return }
        
        let rect = NSRect(
            x: min(start.x, currentPoint.x),
            y: min(start.y, currentPoint.y),
            width: abs(currentPoint.x - start.x),
            height: abs(currentPoint.y - start.y)
        )
        
        currentRect = rect
        updateSizeLabel()
    }
    
    private func updateSizeLabel() {
        guard let rect = currentRect, let label = sizeLabel else { return }
        
        let text = String(format: "%.0f × %.0f", rect.width, rect.height)
        label.stringValue = text
        
        // 更新标签位置
        var labelFrame = label.frame
        labelFrame.origin = NSPoint(
            x: rect.midX - labelFrame.width/2,
            y: rect.maxY + 5
        )
        label.frame = labelFrame
    }
    
    override func draw(_ dirtyRect: NSRect) {
        super.draw(dirtyRect)
        
        guard let context = NSGraphicsContext.current?.cgContext else { return }
        
        if let rect = currentRect {
            // 清除选中区域的半透明背景
            context.setBlendMode(.clear)
            context.fill(rect)
            
            // 绘制选区边框
            context.setBlendMode(.normal)
            context.setStrokeColor(NSColor.white.cgColor)
            context.setLineWidth(1.5)
            context.stroke(rect.insetBy(dx: -0.5, dy: -0.5))
            
            // 绘制边角标记
            drawCornerMarkers(in: rect, context: context)
        }
    }
    
    private func drawCornerMarkers(in rect: NSRect, context: CGContext) {
        let markerLength: CGFloat = 10
        let corners = [
            (rect.minX, rect.minY, 0, 0),      // 左下
            (rect.maxX, rect.minY, -1, 0),     // 右下
            (rect.minX, rect.maxY, 0, -1),     // 左上
            (rect.maxX, rect.maxY, -1, -1)     // 右上
        ]
        
        context.setStrokeColor(NSColor.white.cgColor)
        context.setLineWidth(2)
        
        for (x, y, xDirection, yDirection) in corners {
            // 水平线
            context.move(to: CGPoint(x: x, y: y))
            context.addLine(to: CGPoint(x: x + CGFloat(xDirection) * markerLength, y: y))
            
            // 垂直线
            context.move(to: CGPoint(x: x, y: y))
            context.addLine(to: CGPoint(x: x, y: y + CGFloat(yDirection) * markerLength))
        }
        
        context.strokePath()
    }
    
    private func captureSelectedArea(_ rect: NSRect) -> NSImage? {
        guard Thread.isMainThread else {
            os_log("Attempted to capture screenshot from non-main thread", log: logger, type: .error)
            return nil
        }
        
        guard let screen = window?.screen else {
            os_log("Failed to get screen", log: logger, type: .error)
            return nil
        }
        
        // 将窗口坐标转换为屏幕坐标
        let windowFrame = window?.frame ?? .zero
        let screenRect = screen.frame
        
        // 计算实际的截图区域
        let captureRect = CGRect(
            x: windowFrame.minX + rect.minX,
            y: screenRect.height - (windowFrame.minY + rect.maxY),
            width: rect.width,
            height: rect.height
        )
        
        os_log("Capturing screenshot with rect: %{public}@", log: logger, type: .debug, String(describing: captureRect))
        
        // 创建截图
        guard let cgImage = CGWindowListCreateImage(
            captureRect,
            .optionOnScreenOnly,
            kCGNullWindowID,
            .bestResolution
        ) else {
            os_log("Failed to create CGImage", log: logger, type: .error)
            return nil
        }
        
        return NSImage(cgImage: cgImage, size: rect.size)
    }
}
